<template>
  <div class="edit-user-container">
    <el-card class="edit-user-card">
      <template #header>
        <div class="card-header">
          <h2>编辑用户</h2>
        </div>
      </template>

      <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="120px" :disabled="submitting || loading"
        class="user-form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="新密码（选填）" prop="password" tip="不修改密码请保持为空">
          <el-input v-model="userForm.password" type="password" placeholder="请输入新密码" />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="userForm.confirmPassword" type="password" placeholder="请再次输入新密码" />
        </el-form-item>

        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>

        <el-form-item label="角色" prop="roleId">
          <el-select v-model="userForm.roleId" placeholder="请选择角色">
            <el-option label="管理员" value="1" />
            <el-option label="教师" value="2" />
            <el-option label="学生" value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
            <el-radio label="保密">保密</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item v-loading="loading">
          <div class="form-actions">
            <el-button type="primary" @click="handleSubmit" :loading="submitting">保存修改</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { get, postJson } from '../../utils/api'

const router = useRouter()
const route = useRoute()

// 表单引用
const userFormRef = ref<InstanceType<typeof ElForm> | null>(null)

// 表单数据
const userForm = reactive({
  userId: '',
  username: '',
  password: '',
  confirmPassword: '',
  realName: '',
  roleId: '',
  gender: '保密',
  phone: '',
  email: ''
})

// 加载状态
const loading = ref(false)
const submitting = ref(false)

// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符之间', trigger: 'blur' }
  ],
  password: [
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value && value.length < 6 || value.length > 20) {
          callback(new Error('密码长度在 6 到 20 个字符之间'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (userForm.password && value !== userForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '真实姓名长度在 2 到 20 个字符之间', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  email: [
    {
      pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
      message: '请输入正确的邮箱地址',
      trigger: 'blur'
    }
  ]
})

// 获取用户信息
const getUserInfo = async () => {
  const userId = route.query.userId
  if (!userId) {
    ElMessage.error('用户ID不存在')
    router.push('/admin/user/list')
    return
  }

  loading.value = true
  try {
    const result = await get(`/admin/user/${userId}`)

    if (result.code === 200 && result.data) {
      const user = result.data
      userForm.userId = user.userId
      userForm.username = user.username
      userForm.realName = user.realName
      userForm.roleId = user.roleId?.toString() || ''
      userForm.gender = user.gender || '保密'
      userForm.phone = user.phone || ''
      userForm.email = user.email || ''
    } else {
      ElMessage.error(result.msg || '获取用户信息失败')
      router.push('/admin/user/list')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('网络错误，请检查后端服务')
    router.push('/admin/user/list')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return

  try {
    // 表单验证
    await userFormRef.value.validate()

    // 设置提交状态
    submitting.value = true

    // 准备请求数据
    const submitData = {
      userId: parseInt(userForm.userId),
      username: userForm.username,
      realName: userForm.realName,
      roleId: parseInt(userForm.roleId),
      gender: userForm.gender,
      phone: userForm.phone || '',
      email: userForm.email || ''
    }

    // 如果输入了密码，添加密码字段
    if (userForm.password) {
      ; (submitData as any).password = userForm.password
    }

    // 发送请求
    const result = await postJson('/admin/user/update', submitData)

    if (result.code === 200) {
      ElMessage.success('用户修改成功')
      // 返回用户列表页面
      router.push('/admin/user/list')
    } else {
      ElMessage.error(result.msg || '用户修改失败')
    }
  } catch (error) {
    if (error !== false) { // 如果不是表单验证失败
      console.error('修改用户失败:', error)
      ElMessage.error('网络错误，请检查后端服务')
    }
  } finally {
    submitting.value = false
  }
}

// 取消操作
const handleCancel = () => {
  // 返回用户列表页面
  router.push('/admin/user/list')
}

// 页面加载时获取用户信息
onMounted(() => {
  getUserInfo()
})
</script>

<style scoped>
/* 重置样式并确保容器填满整个屏幕 */
:deep(.el-card) {
  width: 100% !important;
  max-width: none !important;
  margin: 0 !important;
  border-radius: 0;
  border: none;
}

/* 外层容器完全填充满屏幕 */
.edit-user-container {
  padding: 0 !important;
  min-height: 100vh;
  height: 100vh;
  background-color: #fff;
  width: 100vw !important;
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  overflow: hidden;
}

/* 卡片样式 */
.edit-user-card {
  width: 100% !important;
  max-width: none !important;
  margin: 0 !important;
  padding: 0 !important;
  border: none;
  background-color: #fff;
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 头部样式 */
.card-header {
  padding: 20px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

/* 表单样式 */
.user-form {
  padding: 20px;
  width: 100% !important;
  max-width: none !important;
  margin: 0 !important;
  background-color: #fff;
  flex: 1;
}

/* 表单项样式 */
:deep(.el-form-item) {
  margin-bottom: 22px;
}

:deep(.el-form-item__content) {
  width: 100%;
}

/* 输入框样式 */
:deep(.el-input__wrapper),
:deep(.el-select__wrapper) {
  width: 100%;
  max-width: 500px;
}

/* 按钮区域样式 */
.form-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-start;
  margin-top: 20px;
}
</style>

/* 全局样式重置，确保整个页面背景一致 */
<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body, html {
  width: 100% !important;
  height: 100% !important;
  background-color: #fff !important;
  overflow: hidden;
}

#app {
  width: 100% !important;
  height: 100% !important;
  background-color: #fff !important;
}
</style>